package com.bvbot.core.domain;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.bvbot.db.DbTool;

public abstract class AbstractDomainObject implements DomainObject {

	private Long id;

	private static final SimpleDateFormat TO_SQL_DATE_PATTERN = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	@Override
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Override
	public void toDb(Connection conn) throws IOException {
		try {
			if (getId() == null) {
				insertThisIntoDb(conn);
			} else {
				updateThisIntoDb(conn);
			}
		} catch (SQLException e) {
			throw new IOException("SQL Exception occured in toBase", e);
		}
	}

	protected void updateThisIntoDb(Connection conn) throws SQLException {
		String updateSql = getUpdateSql();
		DbTool.execute(conn, updateSql, true);
	}

	private void insertThisIntoDb(Connection conn) throws SQLException {
		String insertSql = getInsertSql();
		DbTool.execute(conn, insertSql, true);
	}

	protected String getSqlStringFor(Date dateValue) {
		return '\'' + TO_SQL_DATE_PATTERN.format(dateValue) + '\'';
	}

	protected abstract String getUpdateSql();

	protected abstract String getInsertSql();

}
